package com.live.shop.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.model.AudioFileModel;
import com.live.shop.tool.FileUtils;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class AudioFileListActivity extends BaseActivity {
    ImageButton audio_file_back;
    TextView audio_file_reload;
    TextView audio_file_ok;
    EditText audio_file_search;
    RecyclerView audio_file_recyclerview;
    List<AudioFileModel> list = new ArrayList<>();
    List<AudioFileModel> audioList;
    MyAdapter adapter;
    AudioFileModel SelectModel;
    boolean isPlaying = false;
    int PlayingPosition = -1;
    //播放器
    MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_file_list);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        audioList = FileUtils.getMisicList(getApplicationContext());

        audio_file_back = findViewById(R.id.audio_file_back);
        audio_file_reload = findViewById(R.id.audio_file_reload);
        audio_file_ok = findViewById(R.id.audio_file_ok);
        audio_file_search = findViewById(R.id.audio_file_search);
        audio_file_recyclerview = findViewById(R.id.audio_file_recyclerview);

        audio_file_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        audio_file_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(SelectModel != null){
                    Intent intent = new Intent();
                    intent.putExtra("model",SelectModel);
                    setResult(-1,intent);
                    finish();
                }else{
                    ToastUtils.Setinfo(getApplicationContext(),"请选择音频",2);
                }
            }
        });
        audio_file_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //多线程处理睡眠
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }
        });
        audio_file_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                searchDisplayName(s.toString());
            }
        });

        list.addAll(audioList);
        adapter = new MyAdapter();
        audio_file_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        audio_file_recyclerview.setAdapter(adapter);
    }
    @SuppressLint("NotifyDataSetChanged")
    public void searchDisplayName(String search_info){
        list.clear();
        if(search_info.equals("")){
            list.addAll(audioList);
        }else{
            for (AudioFileModel model:audioList) {
                if(model.getDisplayName().contains(search_info)){
                    list.add(model);
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_audio_file, parent, false));
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyAdapter.MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;
            AudioFileModel model = list.get(position);

            if(SelectModel != null && SelectModel.getId() == model.getId()){
                mholder.item_audio_linearlayout.setBackgroundResource(R.drawable.bg_shape_dae6f2_10dip);
            }else{
                mholder.item_audio_linearlayout.setBackgroundResource(R.drawable.bg_shape_white_10dip);
            }
            if(PlayingPosition == position){
                mholder.item_audio_play.setImageResource(R.mipmap.icon_audio_pause);
            }else{
                mholder.item_audio_play.setImageResource(R.mipmap.icon_audio_player);
            }
            mholder.item_audio_tilte.setText(model.getTilte());
            mholder.item_audio_album.setText(model.getAlbum());
            mholder.item_audio_artist.setText(model.getArtist());
            mholder.item_audio_url.setText(model.getUrl());
            mholder.item_audio_display_name.setText(model.getDisplayName());
            mholder.item_audio_duration.setText(GetUtil.secToTime(model.getDuration()));

            mholder.item_audio_play.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void onClick(View view) {
                    String music_url = model.getUrl();
                    File file = new File(music_url);
                    if(!file.exists()){
                        ToastUtils.Setinfo(getApplicationContext(),"文件不存在，请加载媒体库进行更新",2);
                        return;
                    }
                    if(isPlaying){
                        //播放中，则取消播放
                        isPlaying = false;
                        mediaPlayer.stop();
                        mediaPlayer.release();

                        if(PlayingPosition == position){
                            //暂停
                            PlayingPosition = -1;
                            notifyDataSetChanged();
                            return;
                        }
                    }
                    //开始播放
                    PlayingPosition = position;
                    isPlaying = true;
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(music_url));
                        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            public void onCompletion(MediaPlayer mediaPlayer) {
                                mediaPlayer.release();
                                isPlaying = false;
                                PlayingPosition = -1;
                                notifyDataSetChanged();
                            }
                        });
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    notifyDataSetChanged();
                }
            });
            mholder.itemView.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void onClick(View view) {
                    SelectModel = model;
                    notifyDataSetChanged();
                }
            });
            mholder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    dialog_item_delete(holder.getBindingAdapterPosition());
                    return true;
                }
            });
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            LinearLayout item_audio_linearlayout;
            TextView item_audio_display_name;
            ImageView item_audio_play;
            TextView item_audio_duration;
            TextView item_audio_tilte;
            TextView item_audio_artist;
            TextView item_audio_album;
            TextView item_audio_url;

            public MyViewHolder(View itemView) {
                super(itemView);
                item_audio_linearlayout = itemView.findViewById(R.id.item_audio_linearlayout);
                item_audio_display_name = itemView.findViewById(R.id.item_audio_display_name);
                item_audio_play = itemView.findViewById(R.id.item_audio_play);
                item_audio_duration = itemView.findViewById(R.id.item_audio_duration);
                item_audio_tilte = itemView.findViewById(R.id.item_audio_tilte);
                item_audio_artist = itemView.findViewById(R.id.item_audio_artist);
                item_audio_album = itemView.findViewById(R.id.item_audio_album);
                item_audio_url = itemView.findViewById(R.id.item_audio_url);
            }
        }
    }

    public void dialog_item_delete(int position){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_item_filedelete);
        final TextView diaglog_delete_file_title = window.findViewById(R.id.diaglog_delete_file_title);
        final TextView diaglog_delete_ok = window.findViewById(R.id.diaglog_delete_file_ok);
        final TextView diaglog_delete_no = window.findViewById(R.id.diaglog_delete_file_no);

        String title = "删除文件 - "+list.get(position).getDisplayName();
        diaglog_delete_file_title.setText(title);

        diaglog_delete_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file = new File(list.get(position).getUrl());
                if(file.exists()) file.delete();
                adapter.notifyItemRemoved(position);
                list.remove(position);
                dialog.dismiss();
            }
        });
        diaglog_delete_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }
    //多线程处理睡眠
    int reloadNum = 0;
    Timer timer;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //开始加载
                    ToastUtils.Setinfo(getApplicationContext(),"正在加载媒体库，请稍后",1);
                    audio_file_reload.setText("加载中...");
                    audio_file_reload.setClickable(false);
                    //强制更新媒体库
                    MediaScannerConnection.scanFile(getApplicationContext(),new String[] { Environment.getExternalStorageDirectory().getAbsolutePath() }, new String[] { "audio/*" },new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            timer.cancel();
                            Message message = new Message();
                            message.what = 3;
                            handler.sendMessage(message);
                        }
                    });
                    //每隔1秒查询
                    timer = new Timer();
                    timer.schedule(new Task(),0,    1000);
                    break;
                case 1:
                    //查询
                    reloadNum ++;
                    List<AudioFileModel> audioList2 = FileUtils.getMisicList(getApplicationContext());
                    if(reloadNum >= 30){
                        timer.cancel();
                        ToastUtils.Setinfo(getApplicationContext(),"媒体库暂无更新",2);
                        audio_file_reload.setText("加载媒体库");
                        audio_file_reload.setClickable(true);
                    }else{
                        if(audioList2.size() != audioList.size()){
                            timer.cancel();
                            Message message = new Message();
                            message.what = 3;
                            handler.sendMessage(message);
                        }
                    }
                    break;
                case 3:
                    //查询
                    audioList.clear();
                    audioList = FileUtils.getMisicList(getApplicationContext());
                    searchDisplayName(audio_file_search.getText().toString());
                    ToastUtils.Setinfo(getApplicationContext(),"媒体库更新完毕",1);
                    audio_file_reload.setText("加载媒体库");
                    audio_file_reload.setClickable(true);
                    break;
            }
        }
    };

    class Task extends TimerTask {
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放MediaPlayer资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}